<template>
	<div class="collapse">
		<div
			class="item"
			v-for="(item, index) in list"
			:key="index"
			:style="`height: ${
				currentIndex === index
					? (titleHeightList[index] + contentHeightList[index])
					: titleHeightList[index]
			}px`"
		>
			<div class="title" @click="onCollapse(index)">{{ item.title }}</div>
			<div class="content">
				{{ item.content }}
			</div>
		</div>
	</div>
</template>

<script>
export default {
	data() {
		return {
			currentIndex: 0,
			list: [
				{
					title: "title 1",
					content: "content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1",
				},
				{
					title: "title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2  title 2 title 2 title 2 title 2 title 2title 2",
					content: "content 2",
				},
				{
					title: "title 3",
					content: "content 3",
				},
			],
			titleHeightList: [],
			contentHeightList: [],
		};
	},
	methods: {
		onCollapse(index) {
			// 如果点击的是已经展开的当前项 则关闭当前项
			if (this.currentIndex === index) {
				this.currentIndex = -1;
			} else {
				// 否则展开当前项
				this.currentIndex = index;
			}
		},
		setHeightList() {
			// 获取所有content的高度
			const contentList = document.querySelectorAll(".collapse .content");
			this.contentHeightList = Array.from(contentList).map(
				(el) => el.offsetHeight
			);
			// 获取所有title的高度
			const titleList = document.querySelectorAll(".collapse .title");
			this.titleHeightList = Array.from(titleList).map(
				(el) => el.offsetHeight
			);
		},
	},
	mounted() {
		this.setHeightList();
		window.addEventListener("resize", this.setHeightList);
	},
	beforeDestroy() {
		window.removeEventListener("resize", this.setHeightList);
	},
};
</script>

<style scoped>
.item {
	overflow: hidden;
	transition: all 1s;
}
.title {
	background-color: #f5f5f6;
	border-bottom: 1px solid #ccc;
}
.content {
	padding: 4px;
	box-sizing: border-box;
}
</style>